<!-- 结算应付作业：蹇泽阳 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :searchImg="false" :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex AIC">
          <h1 class="f16">结算资料</h1>
          <el-date-picker
            class="ml10 mr10"
            v-model="month"
            type="month"
            placeholder="请输入结算月份"
            format="YYYY/MM"
            value-format="YYYYMM"
            style="width: 150px"
          />
          <el-select-v2 :options="VenderOptions" style="width: 100px" v-model="vender" placeholder="厂商" clearable filterable></el-select-v2>
          <el-button class="primaryBth ml10" type="primary" size="default" @click="settlementBtn">结算</el-button>
        </div>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
          @selectList="selectTableList"
          :summaryData="summaryData"
          summary
          :outTableHeight="110"
        />
        <el-card shadow="never" :body-style="{ padding: '5px' }">
          <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
        </el-card>
      </el-card>

      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex AIC">
          <h1 class="f16">结算明细</h1>
          <el-button class="primaryBth ml10" type="primary" size="default" @click="exportBtn">导出</el-button>
        </div>

        <Table
          :tableHeader="tableHeader2"
          :tableData="tableData2"
          class="mt10"
          :isLoading="isLoading2"
          @currentRow="currentRow2"
          :TableHeight="50"
          :summaryData="summaryData2"
          summary
        />
        <div class="flex AIC mt10">
          <div class="flex AIC">
            <h1 class="f16">付款记录</h1>
            <AddOne :tableHeader="tableHeader3" :tableData="tableData3" @Save="Save3" @AddHandle="AddHandle3" />
            <JDialog :tableHeader="tableHeader3" @removeOne="removeOne3" :currentTableRow="currentTableRow3" :unEdit="true" :unAdd="true" />
          </div>
          <el-button class="primaryBth ml10" type="primary" size="default" @click="finalPaymentBtn">尾款处理</el-button>
          <h1 class="f16 ml10 mr10">未付款金额:</h1>
          <el-input v-model="unpaid" placeholder="0" disabled @change="" style="width: 100px"></el-input>
        </div>
        <JTable
          :tableHeader="tableHeader3"
          :tableData="tableData3"
          class="mt10"
          :isLoading="isLoading3"
          @currentRow="currentRow3"
          :TableHeight="50"
        />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import { message } from '@/utils/resetMessage'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'SettlementPayablesKl'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import type { formListType } from '@/components/Find/index.vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
const month = ref('')
const vender = ref('')
const VenderOptions = ref([]) as any
const exportBtn = async () => {
  const res = (await fileRequest.post(`/ryFinance/apAmtDetail/export?slipNo=${currentTableRow.value.slipNo}`, {
    pageNum: -1,
    pageSize: -1
  })) as any
  const link = document.createElement('a') // 利用a标签自定义下载文件名
  let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
  link.style.display = 'none'
  //设置连接
  link.href = window.URL.createObjectURL(blob)
  const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
  link.download = FileName //自定义文件名字
  document.body.appendChild(link)
  //模拟点击事件
  link.click()
  document.body.removeChild(link)
}
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '单据号码',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '结算月份',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '指令',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '结算日期',
    dateValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '送货单号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '材料名称',
    inputValue: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未检核',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已检核',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '未付',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已付',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
]) as any

const formList2 = ref([
  {
    type: 'button',
    checkboxLabel: '取消结算'
  },
  {
    type: 'button',
    checkboxLabel: '打印'
  },
  {
    type: 'button',
    checkboxLabel: '打勾记录检核'
  },
  {
    type: 'button',
    checkboxLabel: '打勾记录取消检核'
  },
  {
    type: 'button',
    checkboxLabel: '导出'
  },
  {
    type: 'button',
    checkboxLabel: '导出汇总'
  }
])
const findClicked = (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
}
const findClicked2 = async (content: string) => {
  if (content === '导出汇总') {
    const res = (await fileRequest.post(`/ryFinance/apAmtDetail/smr/export?slipNo=${currentTableRow.value.slipNo}`, {
      pageNum: -1,
      pageSize: -1
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
  if (content === '置空') {
    formList2.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '打勾记录检核') {
    const res = (await LoginWork.put(
      `/ryFinance/apAmtCfm?cfmFlag=Y`,
      selectedLists.value.map((item: any) => item.slipNo)
    )) as any
    if (res.code === 200) {
      ElMessage({
        message: '检核成功',
        type: 'success'
      })
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '打勾记录取消检核') {
    const res = (await LoginWork.put(
      `/ryFinance/apAmtCfm?cfmFlag=null`,
      selectedLists.value.map((item: any) => item.slipNo)
    )) as any
    if (res.code === 200) {
      ElMessage({
        message: '取消检核成功',
        type: 'success'
      })
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '取消结算') {
    const res = (await LoginWork.put(`/ryFinance/apAmtHeadDel?slipNo=${currentTableRow.value.slipNo}`)) as any
    if (res.code === 200) {
      ElMessage({
        message: '取消结算成功',
        type: 'success'
      })
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '导出') {
    const res = (await fileRequest.post(`/ryFinance/apAmtHead/export`, {
      financeYymm: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '结算月份'
      )?.inputValue,
      lotNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '指令'
      )?.inputValue,
      mtlName: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '材料名称'
      )?.inputValue,
      slipDateEnd: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '结算日期'
      )?.dateValue?.[1],
      slipDateStart: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '结算日期'
      )?.dateValue?.[0],
      slipNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '单据号码'
      )?.inputValue,
      vendorName: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商')
        ?.selectValue,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      cfmFlag: cfmFlag(), //	有无欠数(Y/N)	string	body	true
      fkFlag: cfmFlag2()
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}

// 表一模块
const tableHeader = ref([
  {
    width: 110,
    backgroundColor: true,
    label: '单据号码',
    prop: 'slipNo'
  },
  {
    label: '结算日期',
    prop: 'slipDate'
  },
  {
    label: '结算厂商名称',
    prop: 'vendorName'
  },
  {
    label: '结算月份',
    prop: 'financeYymm'
  },
  {
    backgroundColor2: true,
    label: '金额',
    prop: 'amt'
  }
])
const tableData = ref([])
const isLoading = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData = ref<summaryDataType[]>([
  {
    index: 5,
    num: 0
  }
])
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 表格计算函数
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '未检核')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '已检核')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return ''
  } else if (Unaudited.checked) {
    return 0
  } else if (Audited.checked) {
    return 1
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return ''
  }
}
const cfmFlag2 = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '未付')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '已付')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return ''
  } else if (Unaudited.checked) {
    return 0
  } else if (Audited.checked) {
    return 1
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return ''
  }
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/ryFinance/apAmtHeadQuery', {
    financeYymm: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '结算月份'
    )?.inputValue,
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '指令'
    )?.inputValue,
    mtlName: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '材料名称'
    )?.inputValue,
    slipDateEnd: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '结算日期'
    )?.dateValue?.[1],
    slipDateStart: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '结算日期'
    )?.dateValue?.[0],
    slipNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '单据号码'
    )?.inputValue,
    vendorName: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商')
      ?.selectValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    cfmFlag: cfmFlag(), //	有无欠数(Y/N)	string	body	true
    fkFlag: cfmFlag2()
  })
  isLoading.value = false
  tableData.value = tableDataList.dtos.map((item: any) => {
    if (item.cfmFlag === 'Y') item.backgroundColor = '#40E080'
    if (item.fkFlag === 'Y') item.backgroundColor2 = '#40E080'
    return item
  })
  total.value = tableDataList.total
  currentRow()
  summaryData.value[0].num = tableDataList.amtSum
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
  await getTableList2()
  getTableList3()
}
const selectedLists = ref([])
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}
const settlementBtn = async () => {
  if (!month.value || !vender.value) {
    JMessage.warning('请先选择月份和厂商')
    return
  }
  const res = (await LoginWork.put(`/ryFinance/apAmtHeadAdd?financeYymm=${month.value}&vendorName=${vender.value}`)) as any
  if (res.code === 200) {
    JMessage.success('结算成功')
    getTableList()
  } else {
    JMessage.error(res.message)
  }
}

// 表二模块
const tableData2 = ref([])
const isLoading2 = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData2 = ref<summaryDataType[]>([
  {
    index: 5,
    num: 0
  },
  {
    index: 7,
    num: 0
  }
]) as any
// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
// 获取表数据
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList = await service.post<any, any>(`/ryFinance/apAmtDetailQuery?slipNo=${currentTableRow.value.slipNo}`, {
    pageNum: currentPage2.value,
    pageSize: pageSize2.value
  })
  isLoading2.value = false
  tableData2.value = tableDataList.dtos
  total2.value = tableDataList.total
  currentRow2()
  summaryData2.value[0].num = tableDataList.qtySum
  summaryData2.value[1].num = tableDataList.amtSum
}, 300)
onMounted(() => {
  getTableList2()
})
watch(formList2.value, () => {
  getTableList2()
})
// 点击表给另一张表传数据
const currentTable2Row = ref({}) as any
const currentRow2 = async (row: any = tableData.value[0]) => {
  currentTable2Row.value = row
}
const tableHeader2 = ref([
  {
    label: '指令',
    prop: 'lotNo',
    width: '170'
  },
  {
    label: '材料颜色',
    prop: 'mtlColor'
  },
  {
    width: 250,
    label: '材料名称',
    prop: 'mtlName'
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    width: '55'
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    width: '55'
  },
  {
    label: '数量',
    prop: 'qty'
  },
  {
    label: '单价',
    prop: 'price'
  },
  {
    label: '金额',
    prop: 'amt'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '仓管员',
    prop: 'sysUser'
  }
])

// 表三模块
const tableData3 = ref([])
const isLoading3 = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData3 = ref<summaryDataType[]>([
  {
    index: 2,
    num: 0
  },
  {
    index: 4,
    num: 0
  }
])
// 分页器
const currentPage3 = ref(1)
const pageSize3 = ref(40)
const total3 = ref(0)
const handleSizeChange3 = (val: number) => {
  pageSize3.value = val
  getTableList3()
}
const handleCurrentChange3 = (val: number) => {
  currentPage3.value = val
  getTableList3()
}
// 获取表数据
const getTableList3 = debounce(async () => {
  isLoading3.value = true
  let tableDataList = await service.post<any, any>(`/ryFinance/apAmtFkQuery?slipNo=${currentTableRow.value.slipNo}`)
  isLoading3.value = false
  tableData3.value = tableDataList.dtos.map((item: any) => {
    item.addAndUpdate = true
    item.change = 'Y'
    return item
  })
  total3.value = tableDataList.total
  summaryData3.value[0].num = tableDataList.amtSum
  if (summaryData2.value[1].num !== 0) unpaid.value = summaryData2.value[1].num - tableDataList.amtSum
  currentRow3()
}, 500)
const inputChange3 = async (row: any) => {
  if (Number(row.amt) > summaryData2.value[1].num || Number(row.amt) > unpaid.value) {
    JMessage.warning('金额不能大于未付金额')
    return
  }
  row.slipNo = currentTableRow.value.slipNo
  if (row.qty && row.price) row.amt = Number(row.qty) * Number(row.price)
  const res = (await LoginWork.put('/ryFinance/apAmtFkUp', row)) as any
  if (res.code === 200) {
    // JMessage.success('修改成功')
  } else {
    JMessage.error(res.message)
    getTableList3()
  }
}
const tableHeader3 = ref([
  {
    width: 110,
    change: true,
    label: '单据号码',
    prop: 'slipNo'
  },
  {
    change: true,
    label: '付款厂商名称',
    prop: 'vendorName'
  },
  {
    width: 110,
    type: 'dateSingle',
    label: '付款日期',
    prop: 'apCheckDate'
  },
  {
    label: '金额',
    prop: 'amt'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    change: true,
    label: '操作员',
    prop: 'sysUser'
  }
])
const JTableHeader3 = ref([
  {
    type: 'dateSingle2',
    label: '付款日期',
    prop: 'apCheckDate'
  },
  {
    label: '金额',
    prop: 'amt'
  },
  {
    label: '备注',
    prop: 'remark'
  }
])
const currentTableRow3 = ref({}) as any
const currentRow3 = async (row: any = tableData3.value[0]) => {
  currentTableRow3.value = row
}
const AddHandle3 = (obj: any) => {
  obj.slipNo = currentTableRow.value.slipNo
  obj.vendorName = currentTableRow.value.vendorName
}
const Save3 = async (arr: any, deleteArr: any) => {
  const res = (await LoginWork.put('/ryFinance/apAmtFkUp', tableData3.value)) as any
  // 判断请求是否成功
  if (res.code === 200) {
    JMessage.success(res.message)
    getTableList3()
    deleteArr()
  } else {
    JMessage.error(res.message)
  }
}

// 删除
const removeOne3 = async () => {
  if (currentTableRow3.value.item && currentTableRow3.value.slipNo) {
    // 向服务器发送请求，更新外派单信息
    const res = (await LoginWork.post(`/ryFinance/apAmtFkDel?slipNo=${currentTableRow3.value.slipNo}&item=${currentTableRow3.value.item}`)) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success('删除成功')
    } else {
      JMessage.error(res.message)
    }
    // 重新获取表格数据
    getTableList3()
  } else {
    const index = tableData2.value.findIndex((item: any) => item.slipNo === currentTableRow3.value.slipNo)
    tableData2.value.splice(index, 1)
  }
}
const unpaid = ref(0)
// 尾款处理按钮
const finalPaymentBtn = async () => {
  if (selectedLists.value.length === 0) {
    JMessage.error('请选择数据')
    return
  }
  const res = (await LoginWork.put(
    '/ryFinance/aftPayProcess',
    selectedLists.value.map((item: any) => item.slipNo)
  )) as any
  if (res.code === 200) {
    JMessage.success('尾款处理成功')
    setTimeout(() => {
      getTableList3()
    }, 3000)
  } else {
    JMessage.error(res.message)
  }
}

const selectList = async () => {
  let vendorName = await service.get<any, any>('/back/vendorQuery')
  // 插入厂商代码 厂商名称
  vendorName.forEach((item: any, index: any) => {
    if (item === null) return
    formList.value
      .find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商')
      ?.selectOptions?.push({
        optionKey: `${item.vendorName}`,
        optionLabel: `${item.vendorName}`,
        optionValue: `${item.vendorName}`
      })
    VenderOptions.value.push({
      value: `${item.vendorName}`,
      label: `${item.vendorName}`
    })
  })
}
onMounted(() => {
  selectList()
})
</script>

<style lang="less" scoped>
table {
  table-layout: auto !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>
